<template>
  <div class="history-page">
    <div class="page-header">
      <h1 class="page-title">考试历史</h1>
    </div>

    <div v-if="loading" class="loading-container">
      <van-loading type="spinner" size="24px" />
    </div>

    <template v-else>
      <!-- 数据统计 -->
      <div class="stats-card">
        <div class="stats-item">
          <div class="stats-value">{{ statistics.totalCount }}</div>
          <div class="stats-label">参与考试</div>
        </div>
        <div class="stats-item">
          <div class="stats-value">
            {{
              isNaN(statistics.avgScore)
                ? "0.0"
                : statistics.avgScore.toFixed(1)
            }}
          </div>
          <div class="stats-label">平均分数</div>
        </div>
        <div class="stats-item">
          <div class="stats-value">
            {{ isNaN(statistics.passRate) ? "0" : statistics.passRate }}%
          </div>
          <div class="stats-label">通过率</div>
        </div>
      </div>

      <!-- 历史记录列表 -->
      <div class="history-list" v-if="examRecords.length > 0">
        <div
          v-for="record in examRecords"
          :key="record._id"
          class="history-card"
          @click="goToDetail(record._id)"
        >
          <div class="history-info">
            <div class="history-title">
              {{ record.exam_id?.exam_name || "未知考试" }}
            </div>
            <div class="history-time">
              <template
                v-if="record.status === 'completed' && record.submit_time"
              >
                完成时间: {{ formatDate(record.submit_time) }}
              </template>
              <template v-else>
                开始时间: {{ formatDate(record.start_time) }}
              </template>
            </div>
            <div class="history-status" :class="getStatusClass(record.status)">
              {{ getStatusText(record.status) }}
            </div>
          </div>
          <div class="history-score">
            <template v-if="record.status === 'completed'">
              <div class="score-value">{{ record.score || 0 }}</div>
              <div class="score-total">/ {{ record.total_score || 100 }}</div>
            </template>
            <template v-else>
              <div class="score-value">--</div>
              <div class="score-total">/ --</div>
            </template>
          </div>
        </div>

        <div class="history-end" v-if="!hasMore">
          <van-divider>没有更多记录了</van-divider>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else class="empty-state">
        <van-empty description="暂无考试记录" />
      </div>
    </template>

    <!-- 底部导航 -->
    <van-tabbar route>
      <van-tabbar-item icon="home-o" to="/home">首页</van-tabbar-item>
      <van-tabbar-item icon="notes-o" to="/history">历史</van-tabbar-item>
      <van-tabbar-item icon="user-o" to="/profile">我的</van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script setup lang="ts">
import {
  onMounted,
  reactive,
  ref,
} from 'vue';

import { showToast } from 'vant';
import { useRouter } from 'vue-router';

import { IExamRecord } from '@shared/types/exam';

import { examApi } from '../../api/modules/exam';

const router = useRouter();
const loading = ref(true);
const examRecords = ref<IExamRecord[]>([]);
const hasMore = ref(false);

// 统计数据
const statistics = reactive({
  totalCount: 0,
  avgScore: 0,
  passRate: 0,
});

// 获取考试记录
onMounted(async () => {
  try {
    const response: any = await examApi.getExamRecords();
    console.log("历史记录响应:", response);

    // 根据后端返回的数据结构获取记录数组
    const rawRecords = response.data?.data || [];
    console.log("原始历史记录数据:", rawRecords);

    // 处理记录数据，添加缺失的字段
    examRecords.value = rawRecords.map((record: any) => processRecord(record));
    console.log("处理后的历史记录数据:", examRecords.value);

    calculateStatistics();
  } catch (error) {
    console.error("获取考试记录失败", error);
    showToast("获取考试记录失败");
  } finally {
    loading.value = false;
  }
});

// 处理单个记录，添加缺失字段
const processRecord = (record: any) => {
  console.log("处理单个记录:", record);

  // 获取分数数据，优先使用 user_score，然后是 score
  const userScore = record.user_score ?? record.score ?? 0;
  const totalScore = record.total_score ?? 0;

  // 统一处理所有记录
  return {
    ...record,
    id: record._id,
    exam_name: record.exam_id?.exam_name || "未知考试",
    score: userScore,
    total_score: totalScore,
  };
};

// 计算统计数据
const calculateStatistics = () => {
  console.log("计算统计数据，记录数量:", examRecords.value.length);
  console.log("所有记录:", examRecords.value);

  if (!examRecords.value.length) {
    statistics.totalCount = 0;
    statistics.avgScore = 0;
    statistics.passRate = 0;
    return;
  }

  const records = examRecords.value;
  const totalCount = records.length;

  // 只计算已完成的考试
  const completedRecords = records.filter(
    (record) => record.status === "completed"
  );
  console.log("已完成的考试记录:", completedRecords.length, "/", totalCount);

  // 设置基本统计
  statistics.totalCount = totalCount;

  if (completedRecords.length === 0) {
    // 如果没有完成的考试，显示0
    statistics.avgScore = 0;
    statistics.passRate = 0;
    console.log("没有已完成的考试记录");
    return;
  }

  // 计算平均分
  let totalScore = 0;
  let passCount = 0;
  let validScoreCount = 0;

  completedRecords.forEach((record) => {
    const recordScore = Number(record.score) || 0;
    const recordTotalScore = Number(record.total_score) || 100; // 默认总分100

    console.log(
      `记录 ${record._id}: 得分=${recordScore}, 总分=${recordTotalScore}`
    );

    // 只有当总分大于0时才计算
    if (recordTotalScore > 0) {
      totalScore += recordScore;
      validScoreCount++;

      // 通过标准：60%以上
      if (recordScore / recordTotalScore >= 0.6) {
        passCount++;
      }
    }
  });

  const avgScore = validScoreCount > 0 ? totalScore / validScoreCount : 0;
  const passRate =
    completedRecords.length > 0
      ? Math.round((passCount / completedRecords.length) * 100)
      : 0;

  console.log("统计结果:", {
    totalCount,
    completedCount: completedRecords.length,
    avgScore,
    passRate,
    validScoreCount,
    totalScore,
    passCount,
  });

  statistics.avgScore = avgScore;
  statistics.passRate = passRate;
};

// 格式化日期
const formatDate = (dateInput: string | Date) => {
  if (!dateInput) return "--";

  const date = new Date(dateInput);

  // 检查日期是否有效
  if (isNaN(date.getTime())) return "--";

  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");

  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case "completed":
      return "已完成";
    case "in_progress":
      return "进行中";
    case "timeout":
      return "已超时";
    default:
      return "未知状态";
  }
};

// 获取状态样式类
const getStatusClass = (status: string) => {
  switch (status) {
    case "completed":
      return "status-completed";
    case "in_progress":
      return "status-in-progress";
    case "timeout":
      return "status-timeout";
    default:
      return "";
  }
};

// 查看详情
const goToDetail = (id: string) => {
  router.push(`/result/${id}`);
};
</script>

<style scoped>
.history-page {
  padding: 16px 16px 60px;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.page-header {
  margin-bottom: 16px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #323233;
  margin: 0;
}

.stats-card {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.stats-item {
  flex: 1;
  text-align: center;
}

.stats-value {
  font-size: 20px;
  font-weight: 600;
  color: #1989fa;
  margin-bottom: 4px;
}

.stats-label {
  font-size: 12px;
  color: #969799;
}

.history-list {
  margin-top: 20px;
}

.history-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.history-info {
  flex: 1;
}

.history-title {
  font-size: 16px;
  font-weight: 500;
  color: #323233;
  margin-bottom: 8px;
}

.history-time {
  font-size: 12px;
  color: #969799;
  margin-bottom: 4px;
}

.history-status {
  font-size: 12px;
  display: inline-block;
  padding: 2px 6px;
  border-radius: 4px;
  margin-right: 8px;
}

.status-completed {
  color: #07c160;
  background-color: rgba(7, 193, 96, 0.1);
}

.status-in-progress {
  color: #1989fa;
  background-color: rgba(25, 137, 250, 0.1);
}

.status-timeout {
  color: #ee0a24;
  background-color: rgba(238, 10, 36, 0.1);
}

.history-score {
  display: flex;
  align-items: baseline;
}

.score-value {
  font-size: 24px;
  font-weight: 600;
  color: #1989fa;
}

.score-total {
  font-size: 14px;
  color: #969799;
}

.history-end {
  margin-top: 20px;
  color: #969799;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}
</style>
